<template>
    <view class="container">
        <!-- 顶部信息卡片 -->
        <view class="info-card">
            <view class="info-item" @click="showLocationPicker('departure')">
                <view class="info-label">出发地</view>
                <view class="info-value">
                    <text :class="{ 'has-value-color': start_location }">{{ start_location || "请选择" }}</text>
                    <image src="/static/personalCenter/details.png" mode="aspectFill"></image>
                </view>
            </view>
            <view class="info-item" @click="showLocationPicker('destination')">
                <view class="info-label">目的地</view>
                <view class="info-value">
                    <text :class="{ 'has-value-color': end_location }">{{ end_location || "请选择" }}</text>
                    <image src="/static/personalCenter/details.png" mode="aspectFill"></image>
                </view>
            </view>
            <view class="info-item">
                <view class="info-label">途径点</view>
                <view class="info-value">
                    <input class="input" v-model="route" placeholder="请输入途径点" />
                </view>
            </view>
            <view class="info-item" @click="showTimePicker = true">
                <view class="info-label">出发时间</view>
                <view class="info-value">
                    <text :class="{ 'has-value-color': depart_time }">{{ depart_time || "请选择" }}</text>
                    <image src="/static/personalCenter/details.png" mode="aspectFill"></image>
                </view>
            </view>
            <view class="info-item" @click="showCarPicker">
                <view class="info-label">出行车辆</view>
                <view class="info-value">
                    <text :class="{ 'has-value-color': car_type }">{{ car_type || "请选择" }}</text>
                    <image src="/static/personalCenter/details.png" mode="aspectFill"></image>
                </view>
            </view>
            <view class="info-item" @click="showSeatsPicker">
                <view class="info-label">可订座位数</view>
                <view class="info-value">
                    <text :class="{ 'has-value-color': seats }">{{ seats || "请选择" }}</text>
                    <text style="color: #0B1F20;">座</text>
                    <image src="/static/personalCenter/details.png" mode="aspectFill"></image>
                </view>
            </view>
            <view class="info-item">
                <view class="info-label">单座价格</view>
                <view class="info-value">
                    <input class="input" type="number" v-model="price" placeholder="请输入" />
                    <text style="color: #0B1F20; white-space: nowrap;">元/座</text>
                </view>
            </view>
            <view class="suggest-price" v-if="true"><text style="color: #ff7937">系统建议价：</text>{{ recommendedPrice.rec_price || 0 }}元/座</view>
            <view class="info-item">
                <view class="info-label">备注</view>
                <view class="info-value">
                    <input class="input" v-model="remark" placeholder="示例：请勿携带宠物" placeholder-style="color: #999999;" />
                </view>
            </view>
        </view>

        <!-- 操作按钮 -->
        <view class="btn-group">
            <button class="cancel-btn" @click="cancelTrip">下架行程</button>
            <button class="save-btn" @click="saveTrip">保存行程</button>
        </view>

        <!-- 温馨提示 -->
        <view class="tips">
            <text class="tips-content">温馨提示：</text>
            <view class="tips-content">
                <view>1.请保证填写信息真实有效，虚假信息将被封号。</view>
            </view>
        </view>

        <!-- 时间选择器 -->
		<!-- 时间选择器 -->
		<dateTimePicker :show="showTimePicker" @update:show="showTimePicker = $event" @change="onTimeChange" />
        <!-- 车辆选择器 -->
        <u-picker :show="isShowCarPicker" :columns="[columnsCar]" keyName="label" closeOnClickOverlay
            @confirm="confirmCarPicker" @cancel="closeCarPicker"></u-picker>
        <!-- 座位选择器 -->
        <u-picker :show="isShowSeats" :columns="[columnsSeats]" keyName="label" closeOnClickOverlay
            @confirm="confirmSeatsPicker" @cancel="closeSeatsPicker"></u-picker>
    </view>
</template>

<script>
import moment from 'moment'
import dateTimePicker from "../../../common/dateTimePicker.vue";
import { isEmpty } from "@/utils/util";
export default {
    components: {
        dateTimePicker
    },
    data() {
        return {
            tripId: null,
            start_location: '',
            end_location: '',
            route: '',
            depart_time: '',
            depart_time_value: '',
            car_type: '',
            seats: '',
            price: '',
            remark: '',
            showTimePicker: false,
            isShowCarPicker: false,
            isShowSeats: false,
            columnsCar: [],
            columnsSeats: [],
            type: 0,
            lineData: {},
            currenPositionType: '',
            selectedStartLocation: null,
            selectedEndLocation: null,
            recommendedPrice: {}
        }
    },
    onLoad(options) {
        this.tripId = options.id
        this.getTripDetails()
        this.getCarData()
        uni.$on('setLocation', (data) => {
            this.updateTime();
            this.setLocationFu(data)
        })
    },
    onUnload() {
        uni.$off('setLocation')
    },
    methods: {
        updateTime() {
            this.timer = setInterval(() => {
                this.currenPosition = '';
            }, 1000);
        },
        onTimeChange(e) {
			this.$nextTick(function () {
                this.depart_time = `${e.date} ${moment(e.dateTime).format("HH:mm")}`;
                this.depart_time_value = e.dateTime;
			});
			this.closeDateTimePicker();
		},
        closeDateTimePicker() {
            this.showTimePicker = false;
        },
        // 选择的出发地 目的地
        setLocationFu(data) {
            if (this.currenPositionType === "departure") {
                this.selectedStartLocation = data;
                this.start_location = `${data.name} . ${data.title}`// data.name + data.title;
            } else {
                this.selectedEndLocation = data;
                this.end_location = `${data.name} . ${data.title}`;
            }

            if (this.selectedStartLocation && this.selectedEndLocation) {
                this.getRecommendedPrice(
                    this.selectedStartLocation.id,
                    this.selectedEndLocation.id,
                    true
                );
            }
        },
        // 获取系统推荐价格
        async getRecommendedPrice(sid, eid, isUpdate = false) {
            let params = {
                start_id: sid,
                end_id: eid,
            };
            try {
                const data = await this.$http.post("/h5/user/line/getLineRecommendPrice", params);
                if (isEmpty(data.data)) {
					uni.showToast({ title: '您所选的线路暂未开放,请选择其他线路', icon: 'none', duration: 5000 })
					return
				}
                this.recommendedPrice = data.data;
                if (isUpdate) {
                    this.price = data.data.rec_price || 0;
                }
                
            } catch (error) {}
        },
        showLocationPicker(type) {
            this.currenPositionType = type;
            uni.navigateTo({
                url: `/pages/released/location-picker?type=${type}&activeTab=${this.type}&isUpdate=true`,
            });
        },
        showCarPicker() {
            this.isShowCarPicker = true;
        },
        showSeatsPicker() {
            if (!this.car_type) {
                uni.showToast({ title: '请选择车型', icon: 'none' }); return;
            }
            this.isShowSeats = true;
        },
        // 座位数相关
        closeSeatsPicker() {
            this.isShowSeats = false;
        },
        confirmSeatsPicker(e) {
            this.seats = e.value[0].value
            this.closeSeatsPicker();
        },
        async getCarData() {
            try {
                const res = await this.$http.get("/h5/user/carowner/myCars");
                this.columnsCar =
                    res.data &&
                    res.data.map((i) => {
                        return {
                            label: i.brand_model,
                            id: i.id,
                            seats: i.seats,
                        };
                    });
            } catch (error) {
                uni.showToast({ title: error.msg || '获取车辆数据失败', icon: 'none' })
            }
        },
        confirmCarPicker(e) {
            this.car_type = e.value[0].label
            this.car_id = e.value[0].id
            this.columnsSeats = [];
            for (let index = 1; index < e.value[0].seats; index++) {
                const element = `${index}座`;
                let obj = {
                    label: element,
                    value: index
                }
                this.columnsSeats.push(obj)

            }
            this.closeCarPicker();
        },
        closeCarPicker() {
            this.isShowCarPicker = false;
        },
        async getTripDetails() {
            try {
                const res = await this.$http.get(`/h5/line/detail/${this.tripId}`)
                const data = res.data
                this.start_location = `${data.line.start.name} . ${data.line.start_title}`
                this.end_location = `${data.line.end.name} . ${data.line.end_title}`
                this.route = data.line.approach
                this.depart_time = moment(data.line.start_time).format('YYYY-MM-DD HH:mm')
                this.car_type = data.line.brand_model
                this.seats = data.line.current_seats
                this.price = data.line.unit_price
                this.remark = data.line.remark
                this.type = data.line.type === 1 ? 'city' : 'rural'
                this.lineData = data.line
                this.selectedStartLocation = data.line.start
                this.selectedEndLocation = data.line.end
                this.depart_time_value = moment(data.line.start_time).format('YYYY-MM-DD HH:mm:ss')
                this.getRecommendedPrice(data.line.start.id, data.line.end.id, false)
                this.columnsSeats = []
                for (let index = 1; index < data.line.seats; index++) {
                    const element = `${index}座`;
                    let obj = {
                        label: element,
                        value: index
                    }
                    this.columnsSeats.push(obj)

                }

            } catch (error) {
                uni.showToast({ title: '获取行程失败', icon: 'none' })
            }
        },

        async saveTrip() {
            if (!this.start_location) {
                uni.showToast({ title: '请输入出发地', icon: 'none' }); return;
            }
            if (!this.end_location) {
                uni.showToast({ title: '请输入目的地', icon: 'none' }); return;
            }
            if (!this.route) {
                uni.showToast({ title: '请输入途径点', icon: 'none' }); return;
            }
            if (!this.depart_time) {
                uni.showToast({ title: '请选择出发时间', icon: 'none' }); return;
            }
            if (!this.car_type) {
                uni.showToast({ title: '请选择出行车辆', icon: 'none' }); return;
            }
            if (!this.seats) {
                uni.showToast({ title: '请选择订座数', icon: 'none' }); return;
            }
            if (!this.price) {
                uni.showToast({ title: '请输入单座价格', icon: 'none' }); return;
            }
            // 判断价格是否大于系统建议价
            if (Number(this.price) > (Number(this.recommendedPrice.rec_price) + Number(this.recommendedPrice.allow_price_wave))) {
                // 计算总价格
                let totalPrice = (Number(this.recommendedPrice.rec_price) + Number(this.recommendedPrice.allow_price_wave)) * Number(this.columnsSeats[this.columnsSeats.length - 1].value)

                let maxSeats = Math.floor(totalPrice / (Number(this.price)))

                if (Number(this.seats) > maxSeats) {
                    uni.showModal({
                        title: '温馨提示',
                        content: `顺风车不能以盈利为目的，您的发布价格大于平台建议价，本次最多能发布${maxSeats}个座位。`,
                        confirmText: '继续发布',
                        cancelText: '修改价格',
                        success: (res) => {
                            if (res.confirm) {
                                if (Number(this.seats) > maxSeats) {
                                    this.seats = maxSeats;
                                }
                                this.doSaveTrip();
                            } else {
                                this.getRecommendedPrice(
                                    this.selectedStartLocation.id,
                                    this.selectedEndLocation.id,
                                    true
                                );
                            }
                        }
                    });
                    return;
                }
            }
            // 判断已有预订记录!不可修改出发地、目的地等行程信息。如需发布新行程，可点击“下架行程”，然后重新“车主发布”
            if (this.lineData.on_order > 0 && (this.start_location != `${this.lineData.start.name} . ${this.lineData.start_title}` || this.end_location != `${this.lineData.end.name} . ${this.lineData.end_title}`)) {
                uni.showModal({
                    title: '提示',
                    content: '已有预订记录!不可修改出发地、目的地。如需发布新行程，可点击“下架行程”，然后重新“车主发布”',
                    showCancel: false,
                    confirmText: '确定'
                });
                return;
            }
            this.doSaveTrip();

        },
        async doSaveTrip() {
            let params = {
                start_time: this.depart_time_value, // 出发时间 必填
                start_id: (this.selectedStartLocation && this.selectedStartLocation.id) || this.lineData.start_id, // 起点id 必填
                start_title: (this.selectedStartLocation && this.selectedStartLocation.title) || this.lineData.start_title, // 出发点详细地址 必填
                end_id: (this.selectedEndLocation && this.selectedEndLocation.id) || this.lineData.end_id, // 终点id 必填
                end_title: (this.selectedEndLocation && this.selectedEndLocation.title) || this.lineData.end_title, // 终点详细地址 必填
                approach: this.route, // 途径 非必填
                car_id: this.car_id || this.lineData.car_id, // 车辆id 必填
                current_seats: this.seats, // 可预定座位数 必填
                unit_price: this.price, // 单座价格 必填
                remark: this.remarks, // 备注 非必填
            };
            try {
                await this.$http.post(`/h5/user/line/edit/${this.tripId}`, params)
                uni.showToast({ title: '保存成功', icon: 'success' })
                setTimeout(() => { uni.navigateBack() }, 1000)
            } catch (error) { }

        },
        async cancelTrip() {

            if (this.lineData.on_order > 0) {
                uni.showModal({
                    title: '提示',
                    content: '行程已有预订记录，强行下架依然会产生信息费。',
                    confirmText: '确定',
                    cancelText: '取消',
                    success: (res) => {
                        if (res.confirm) {
                            this.confirmCancelTrip()
                        }
                    }
                });
                return;
            }
            // 弹窗确认
            uni.showModal({
                title: '提示',
                content: '确定下架该行程吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.confirmCancelTrip()
                    }
                }
            })
        },
        async confirmCancelTrip() {
            try {
                await this.$http.get(`/h5/user/line/cancel/${this.tripId}`)
                uni.showToast({ title: '下架成功', icon: 'success' })
                this.getTripDetails()
                setTimeout(() => { uni.navigateBack() }, 1000)
            } catch (error) {
                uni.showToast({ title: '下架失败', icon: 'none' })
            }
        }
    }
}
</script>

<style scoped>
.container {
    padding: 20rpx 26rpx;
}

.info-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 40rpx;
    margin-bottom: 20rpx;
}

.info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 34rpx 0;
    border-bottom: 2rpx solid #eee;
}

.info-item:last-child {
    border-bottom: none;
}

.info-label {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 500;
    font-size: 32rpx;
    color: #0B1F20;
    width: 168rpx;
    padding-right: 20rpx;
}

.info-value {
    flex: 1;
    display: flex;
    align-items: center;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 32rpx;
    color: #0B1F20;
    line-height: 48rpx;
}

.info-value .input {
    font-size: 32rpx;
    color: #666666;
    /* text-align: right; */
}

.info-value image {
    width: 32rpx;
    height: 32rpx;
    margin-left: auto;
}

.btn-group {
    display: flex;
    justify-content: space-between;
    margin: 30rpx 0 20rpx 0;
}

.cancel-btn {
    background: #fff;
    color: #ff3f39;
    border: 2rpx solid #ff3f39;
    border-radius: 16rpx;
    font-weight: 500;
    font-size: 36rpx;
    height: 100rpx;
    line-height: 100rpx;
    width: 45%;
}

.save-btn {
    background: linear-gradient(90deg, #ff3f39 0%, #ff7937 100%);
    color: #fff;
    border-radius: 16rpx;
    font-weight: 500;
    font-size: 36rpx;
    height: 100rpx;
    line-height: 100rpx;
    width: 45%;
}

.tips {
    padding: 0 34rpx;
}

.tips-content {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-size: 24rpx;
    color: #999999;
    line-height: 48rpx;
}

.suggest-price {
    font-size: 28rpx;
    color: #999999;
    margin-top: 16rpx;
}
</style>